"use client";
import { useState } from "react";
import NameInput from "@/app/components/NameInput/NameInput";
import cozeApi from "./cozeApi";
import styles from "./page.module.scss";
import UploadObs from "@/app/components/uploadObs/uploadObs";
import Img from "@/app/components/img/img";

interface messages {
  id: number;
  content: string;
  type: string;
  createdAt: string;
  createdBy: string;
  url?: string;
}

interface UserInput {
  content: string;
  type: string;
  url?: string;
}

const AICoze = () => {
  const [messages, setMessages] = useState<messages[]>([
    {
      id: 1,
      content: "Hello, how are you?",
      type: "text",
      createdAt: "2021-01-01",
      createdBy: "AICoze",
    },
  ]);

  const handleUserInput = async (data: UserInput) => {
    console.log(data);
    console.log(messages);

    // 添加用户消息
    const userMessage = {
      id: messages.length + 1,
      type: data.type,
      content: data.content,
      createdAt: new Date().toISOString(),
      createdBy: "User",
      url: data.url || "",
    };

    setMessages((prevMessages) => [...prevMessages, userMessage]);

    try {
      // 构建发送给 AI 的消息内容
      const messageContent = data.url
        ? `${data.content} [文件: ${data.url}]`
        : data.content;

      // 调用 Coze API 获取回复
      const aiResponse = await cozeApi.getMessage(messageContent);
      console.log(aiResponse, "aiResponse");

      // 提取URL的正则表达式，匹配完整的URL
      const urlRegex = /https:\/\/[^\s\)]+/g;
      const aiResponseUrl = aiResponse.match(urlRegex);
      console.log(aiResponseUrl, "aiResponseUrl");

      // 添加 AI 回复
      const aiMessage = {
        id: messages.length + 2,
        type: aiResponseUrl ? "image" : "text", // 如果有URL则类型为image
        content: aiResponse,
        createdAt: new Date().toISOString(),
        createdBy: "AICoze",
        url: aiResponseUrl ? aiResponseUrl[0] : "",
      };

      setMessages((prevMessages) => [...prevMessages, aiMessage]);
    } catch (error) {
      console.error("获取 AI 回复失败:", error);

      // 添加错误消息
      const errorMessage = {
        id: messages.length + 2,
        type: "text",
        content: "抱歉，服务暂时不可用，请稍后再试。",
        createdAt: new Date().toISOString(),
        createdBy: "AICoze",
      };

      setMessages((prevMessages) => [...prevMessages, errorMessage]);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.messagesContainer}>
        {messages.map((message) => (
          <div
            key={message.id}
            className={
              message.createdBy === "AICoze"
                ? styles.messageAICoze
                : styles.messageUser
            }
          >
            {message.type === "file" ? (
              <div
                className={styles.messageFile}
                onClick={() => {
                  window.open(message.url, "_blank");
                }}
              >
                <p>{message.content}</p>
                <Img
                  src={message.url || ""}
                  alt={message.content}
                  width={100}
                  height={100}
                />
              </div>
            ) : message.type === "image" ? (
              <div className={styles.messageImage}>
                <p>{message.content}</p>
                <Img
                  src={message.url || ""}
                  alt="AI生成的图片"
                  width={300}
                  height={300}
                />
              </div>
            ) : (
              <p>{message.content}</p>
            )}
          </div>
        ))}
      </div>
      <div className={styles.inputArea}>
        <div className={styles.uploadObs}>
          <UploadObs
            usetype="coze"
            showFileList={false}
            callback={(file) => {
              handleUserInput({
                content: file.name,
                type: "file",
                url: file.url,
              });
            }}
          />
        </div>
        <div className={styles.nameInput}>
          <NameInput
            placeholder="请输入..."
            buttonText="发送"
            callback={(data) => {
              handleUserInput({
                content: data,
                type: "text",
              });
            }}
          />
        </div>
      </div>
    </div>
  );
};
export default AICoze;
